const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const path = require('path');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 1337;

// 安全中间件
app.use(helmet());

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP 15分钟内最多100个请求
  message: '请求过于频繁，请稍后再试'
});
app.use('/api/', limiter);

// CORS配置
app.use(cors({
  origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
  credentials: true
}));

// 解析JSON和URL编码的请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 路由
app.use('/api/materials', require('./routes/materials'));
app.use('/api/material-types', require('./routes/materialTypes'));
app.use('/api/user-materials', require('./routes/userMaterials'));
app.use('/api/upload', require('./routes/upload'));
app.use('/api/templs', require('./routes/templates'));
app.use('/api/templ-types', require('./routes/templateTypes'));
app.use('/api/font-styles', require('./routes/fontStyles'));
app.use('/api/font-style-types', require('./routes/fontStyleTypes'));
app.use('/api/fonts', require('./routes/fonts'));
app.use('/api/fontborders', require('./routes/fontBorders'));
app.use('/api/sizes', require('./routes/sizes'));
app.use('/api/banners', require('./routes/banners'));
app.use('/api/web-site', require('./routes/webSite'));
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({ error: '接口不存在' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    error: process.env.NODE_ENV === 'production' ? '服务器内部错误' : err.message 
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
  console.log(`📊 健康检查: http://localhost:${PORT}/health`);
});